<?php
/**
 * Created by PhpStorm.
 * User: lenvo
 * Date: 2018/6/24
 * Time: 16:40
 */

namespace app\home\controller;




use think\Db;

class Merauth extends Basic
{
    public function _initialize()
    {
        $this->authRecord = Db::table('sp_mer_auth_record');
        $arr[0]['text']='权限组列表';
        $arr[0]['url']='index';
        $this->assign('third_menu', $arr);
    }
    /**
     * 权限组列表
     * @return [type] [description]
     */
    public function index()
    {
        $list = Db::table('sp_mer_auth')->paginate(15);
        $this->assign('list', $list);
        return $this->fetch();
    }
    /**
     * 权限组增加表单
     */
    public function add()
    {
        if(input('id')) {
            $list = Db::table('sp_mer_auth')->where('id', input('id'))->find();
            $this->assign('data', $list);
        }
        return $this->fetch();
    }
    /**
     * 权限组增加提交
     * @return [type] [description]
     */
    public function goAdd()
    {

        $data['auth_name'] = input('auth_name');
        $data['auth_remark'] = input('auth_remark');
        if(input('status')) {
            $data['status'] = 1;
        } else {
            $data['status'] = 0;
        }
        if($data['auth_name'] == "") {
            return $this->ret->setCode(1)->setMsg('权限名称不能为空')->toJson();
        }
        if(input('id')) {
            $data['uptime'] = time();
            $res = Db::table('sp_mer_auth')->where('id', input('id'))->update($data);
            if($res) {
                return $this->ret->setMsg('修改成功!')->setReload()->toJson();
            } else {
                return $this->ret->setCode(2)->setMsg('修改失败')->toJson();
            }
        } else {
            $data['addtime'] = time();
            $id = Db::table("sp_mer_auth")->insertGetId($data);
            if($id) {
                return $this->ret->setMsg('新增成功!')->setReload()->toJson();
            } else {
                return $this->ret->setCode(3)->setMsg('新增失败')->toJson();
            }
        }
    }
    /**
     * 权限组删除
     * @return [type] [description]
     */
    public function del()
    {

        $where = array('id' => input('id'));
        $result = Db::table('sp_mer_auth')->where($where)->delete();
        if($result) {
            return $this->ret->setMsg('删除成功!')->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('删除失败')->toJson();
        }
    }

    /**
     * @name 权限设置
     * @date   2017.1.19
     */
    public function auth_edit()
    {
        $id = input('id');
        if (IS_POST){
            $menuids = isset($_POST['menuid']) ? $_POST['menuid'] : array();

            $menuids = is_array($menuids) ? $menuids : array();
            $recordIds   = array();
            foreach ($menuids as $menuid) {
                $menu = Db::table("sp_mer_menu")->where(array('id' => intval($menuid)))->field('id,model,controller,action,name,data')->find();
                if ($menu) {
                    $model = $menu['model'];
                    $controller = $menu['controller'];
                    $action = $menu['action'];
                    $data = $menu['data'];
                    $name = strtolower("{$model}/{$controller}/{$action}");
                    $names[] = $name;
                    $currentRecord = Db::table("sp_mer_auth_record")->where(array('auth_id' => $id, 'rule_value' => $name,'data'=>$data))->find();
                    if(!$currentRecord){
                        $recordIds[] = Db::table("sp_mer_auth_record")->insertGetId(array('auth_id' => $id, 'rule_value' => $name, 'data' => $data, 'menu_id'=>$menu['id']));
                    }else{
                        $recordIds[] = $currentRecord['id'];
                    }
                }
            }
            //  取出当前用户所有菜单权限
            $rule_values = Db::table("sp_mer_auth_record")->where("auth_id",$id)->select();
            //  开始筛选不存在的权限并删除
            foreach ($rule_values as $rule_value){
                if(!in_array($rule_value['id'],$recordIds)){
                    Db::table("sp_mer_auth_record")->where("id",$rule_value['id'])->delete();
                }
            }
            return $this->ret->setMsg('修改成功!')->setReload()->toJson();
        }
        return $this->ret->setCode(1)->setMsg('删除失败')->toJson();
    }

    /**
     * @name   权限列表展示
     * @date   2017.1.19
     */
    public function auth_index(){
        $id = input('id');
        $this->assign("id",$id);
        $this->menu = Db::table("sp_mer_menu");
        //拉取所有菜单
        $result = $this->menu->select();
        $newmenus  = array();
        $records = Db::table("sp_mer_auth_record")->where("auth_id",$id)->select();
        $priv_data =array();
        foreach ($records as $record){
            $priv_data[] = $record['data'] ? $record['rule_value'].'/'.$record['data'] : $record['rule_value'];
        }
        foreach ($result as $m){
            $newmenus[$m['id']]=$m;
        }
        //$newResult = array();
        foreach ($result as $n => $t) {
            $result[$n]['checked'] = ($this->_is_checked($t, $id, $priv_data)) ? ' checked' : '';
            $result[$n]['level'] = $this->_get_level($t['id'], $newmenus);
            $result[$n]['style'] = empty($t['pid']) ? '' : 'display:none;';
            $result[$n]['parentid_node'] = ($t['pid']) ? ' class="child-of-node-' . $t['pid'] . '"' : '';
            $result[$n]['parent_id'] = $t['pid'];
            // orm传入tree中时会出现无法创建变量
            //$newResult[$t['id']] = $result[$n]->toArray();
        }
        $menu = new \thans\Common\tree($result);
        $menu->formatArrayForTree('id', 'pid','name');
        $categorys = $menu->get_tree_array(0, '');

        $this->assign("list", $categorys);
        return $this->fetch();
    }

    /**
     *  检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param int $roleid 需要检查的角色ID
     */
    private function _is_checked($menu, $roleid, $priv_data) {

        $app=$menu['model'];
        $model=$menu['controller'];
        $action=$menu['action'];
        $data=$menu['data'];
        $name = $data ? strtolower("$app/$model/$action/$data") : strtolower("$app/$model/$action");
        if($priv_data){
            if (in_array($name, $priv_data)) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }

    }
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
        $array[$id]['parent_id'] = $array[$id]['pid'];
        if ($array[$id]['pid']==0 || empty($array[$array[$id]['pid']]) || $array[$id]['pid']==$id){
            return  $i;
        }else{
            $i++;
            $array[$id]['parent_id'] = $array[$id]['pid'];
            return $this->_get_level($array[$id]['pid'],$array,$i);
        }

    }
}